package com.example.demo.controller;

import com.example.demo.common.AjaxResult;
import com.example.demo.common.Constant;
import com.example.demo.common.PasswordUtil;
import com.example.demo.entity.UserInfo;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 用户控制器
 *
 * @author CY
 * @date 2023/03/13 23:22
 **/
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //注册
    @RequestMapping("/reg")
    public AjaxResult addUser(String username, String password) {
        //非空校验(防止通过其他方式访问后端)
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return AjaxResult.fail(-1, "非法参数请求!");
        }

        //插入操作
        if (userService.addUser(username, PasswordUtil.encrypt(password)) == 1) {
            return AjaxResult.success(1);
        }
        return AjaxResult.fail(500, "注册失败!");
    }

    //登录
    @RequestMapping("/login")
    public int login(String username, String password, HttpSession httpSession) {
        //非空校验(防止通过其他方式访问后端)
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return -1;
        }
        //根据用户名去得到盐值
        final UserInfo userInfo = userService.getPasswordByName(username);
        if (PasswordUtil.decrypt(password, userInfo.getPassword())) {
            httpSession.setAttribute(Constant.SESSION_USERINFO_KEY, userInfo);
            return 1;
        } else {
            return 0;
        }
    }

    //注销
    @RequestMapping("/logout")
    public boolean logout(HttpServletRequest request) {
        final HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(Constant.SESSION_USERINFO_KEY) != null) {
            session.removeAttribute(Constant.SESSION_USERINFO_KEY);

        }
        //注销操作默认注销成功!
        return true;
    }

    //返回个人信息
    @RequestMapping("/my-info")
    public UserInfo getMyInfo(HttpServletRequest request) {
        final HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(Constant.SESSION_USERINFO_KEY) != null) {
            final UserInfo userInfo = (UserInfo) session.getAttribute(Constant.SESSION_USERINFO_KEY);
            userInfo.setPassword("");
            return userInfo;
        }
        return null;
    }

    @RequestMapping("/my-info2")
    public UserInfo getMyInfo2(Integer id) {
        if (id == null || id < 0) {
            return null;
        }
        return userService.getUserinfoByArtId(id);
    }

}
